package com.bj58.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.junit.Test;

public class ReflectionUtils {

	public static List<String> scanPackage(String basePackages, List<String> classList) {
		String rootDir = ReflectionUtils.class.getClass().getResource("/").getPath();
		String source = rootDir + basePackages.replace(".", File.separator);
		File sourceFile = new File(source);
		File[] files = sourceFile.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				findClassByPackage(basePackages, file.getPath(), classList);
			} else if (file.isFile() && file.getName().startsWith(".class")) {
				String className = file.getAbsolutePath().replace("\\", ".");
				String clazzName = className.substring(className.indexOf(basePackages));
				String clazz=clazzName.substring(0, clazzName.indexOf(".class"));
				classList.add(clazz);
			}
		}

		return classList;
	}

	private static void findClassByPackage(String basePackages, String path, List<String> classList) {
		
		File sourceFile = new File(path);
		File[] files = sourceFile.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				findClassByPackage(basePackages, file.getPath(), classList);
			} else if (file.isFile() && file.getName().endsWith(".class")) {
				String className = file.getAbsolutePath().replace("\\", ".");
				String clazzName = className.substring(className.indexOf(basePackages));
				String clazz=clazzName.substring(0, clazzName.indexOf(".class"));
				classList.add(clazz);
			}
		}
	}
	
	public static void  getAnnotation(String clazzName){
		
		try {
			//Class clazz=ReflectionUtils.class.getClass().getClassLoader().loadClass(clazzName);
			Class clazz=Class.forName(clazzName);
			Field[] fields=clazz.getDeclaredFields();
			for (Field field:fields) {
				field.setAccessible(true);
				Inject inject=field.getAnnotation(Inject.class);
				if(inject!=null){
					System.out.println(inject);
				}
				
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test(){
		getAnnotation("com.bj58.di.factory.BookFactory4");
	}
	public static void main(String[] args) {
//		String sc = "com.bj58.di";
//		List<String> fileList = new ArrayList<>();
//		scanPackage(sc, fileList);
//		System.out.println(fileList.size());
		getAnnotation("com.bj58.di.factory.BookFactory4");
	}

}
